<template>
  <div class="root">
    <div class="login-form">
      <div><label>用户名<input type="text" placeholder="user name" v-model="username"></label></div>
      <div><label>密  码<input type="password" placeholder="password" v-model="password"></label></div>
      <div><label>记住密码<input type="checkbox" v-model="remember"></label></div>
      <div><button @click="login_clicked">登录系统</button> </div>
      <div>
        <label>TOKEN :<input type="text" placeholder="get token" v-model="token"></label>
      </div>
    </div>
  </div>
</template>

<script>
import esync from './requests';
import {loadAuthInfo, saveAuthInfo} from './auth_storage';

export default {
  name: 'LoginView',
  data() {
    return {
      username: 'esync',
      password: '123456',
      remember: false,
      token: '',
    }
  },
  created() {
    // load from storage
    let authInfo = loadAuthInfo();
    if(!!!authInfo) {
      return;
    }
    this.token = authInfo.token;
    esync.setToken(authInfo.userId, this.token);
  },
  methods: {
    login_clicked() {
      let remember = 0;
      if(this.remember === true) {
        remember = 1;
      }
      esync.Login(this.username, this.password, remember).then(res=>{
        console.log(JSON.stringify(res.data));
        this.token = res.data.access_token;
        let userId = res.data.user_id;
        esync.setToken(userId, this.token);
        saveAuthInfo(userId, this.token);
      }).catch(err=>{
        console.info(err);
      });
    }
  }
}
</script>

<style scoped>
.login-form {
  margin-bottom: 15px;
}
</style>